package de.karlNet.sshTray.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.springframework.stereotype.Component;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import de.karlNet.sshTray.model.Settings;

@Component
public class SettingsController {
	private XStream xStream = new XStream(new DomDriver());
	private File file = new File("configuration.xml");
//	private static SettingsController settingsController;

//	public static void initSettings() {
//		if(settingsController==null) {
//			settingsController = new SettingsController();
//		}
//	}
	
	public void updateSettings(Settings settings) {
		FileWriter fileReader;
		try {
			fileReader = new FileWriter("configuration.xml");
			xStream.toXML(settings, fileReader);
			fileReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Settings loadSettings() {
		FileReader reader = null;
		try {
			reader = new FileReader(this.file);
			Settings settings = (Settings) xStream
					.fromXML(reader);
			reader.close();
			return settings;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@javax.annotation.PostConstruct
	public void init() {
		if(!file.exists()) {
			try {
				file.createNewFile();
				Settings settings = new Settings();
				this.updateSettings(settings);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} 
	}
	

}
